package com.boco.fc.auto.deploy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

/**
 * 
 * @author yangfeng
 * 2017年9月30日 15:12:50
 */
public class Recover {
	
	public Logger log = Logger.getLogger(this.getClass());
	
	public static Recover getInstance(){
		return new Recover();
	}
	
	private Map<String, Map<String, Object>> serverMap;
	
	//删除文件数
	private int deleteCount = 0;
	
	//恢复文件数
	private int recoverCount = 0;
	
	// 开始处理时间
	private long startTime = 0L;

	// 处理结束时间
	private long endTime = 0L;
	
	
	/**
	 * start Deploy
	 * @param xmlPath
	 */
	public void start(String xmlPath,String backupPath) throws Exception {
		log.info("恢复开始.............");
		XmlUtil xmlUtil = new XmlUtil();
		//执行恢复
		List<Map<String, Object>> serverList = xmlUtil.parseJdom(xmlPath);
		serverMap = new HashMap<String, Map<String, Object>>();
		for(Map<String, Object> server:serverList){
			serverMap.put((String) server.get("host"), server);
		}
		this.executeRecover(serverMap,backupPath);
		log.info("恢复结束。");
	}

	/**
	 * 
	 * @param serverMap
	 * @param backupDate
	 * @throws Exception
	 */
	private void executeRecover(Map<String, Map<String, Object>> serverMap, String backupPath) throws Exception {
		File file = new File(backupPath);
		if(file.isDirectory()){//恢复备份日期下的所有内容
			File [] ips = file.listFiles();
			if(ips.length > 0 ){
				for(File ip:ips){
					this.recoverDeploy(ip);
				}
			}
		}else{
			this.recoverDeploy(file);//恢复指定内容
		}
	}

	/**
	 * 恢复文件
	 * @param recoverFile
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private void recoverDeploy(File recoverFile) throws Exception {
		this.initCount();
		List<String> recoverList = this.readRecoverFile(recoverFile);
		String ip = recoverFile.getName().substring(0, recoverFile.getName().length()-4);
		Map server = this.serverMap.get(ip);
		SSH2Util sshUtil = new SSH2Util(server);
		sshUtil.connectAndAuth();
		for(String record:recoverList){
			String node [] = record.split("\\|");
			if("add".equals(node[0])){
				deleteCount += 1;
				sshUtil.rmFile(node[1]);
			}else if("update".equals(node[0])){
				recoverCount += 1;
				sshUtil.uploadFile(node[2], node[1]);
			}
		}
		sshUtil.closeConnection();
		this.dealResult(ip);
	}

	/**
	 * 读取发布时创建的恢复文件
	 * @param recoverFile
	 * @return
	 * @throws Exception
	 */
	private List<String> readRecoverFile(File recoverFile) throws Exception {
		log.info("读取文件" + recoverFile.getAbsolutePath());
		List<String> recoverList = new ArrayList<String>();
		FileReader fileReader=new FileReader(recoverFile);  
		BufferedReader bufferedReader=new BufferedReader(fileReader);  
	    String read=null;  
	    while((read=bufferedReader.readLine())!=null){  
	    	recoverList.add(read);
	    }  
	    fileReader.close();
	    bufferedReader.close();
		return recoverList;
	}
	
	/**
	 * 初始化发布计数
	 */
	private void initCount() {
		this.deleteCount = 0; // 删除文件数
		this.recoverCount = 0; // 恢复文件数
		this.startTime = System.currentTimeMillis();
	}
	
	/**
	 * 打印远程处理情况日志
	 */
	private void dealResult(String serverIp) {
		this.endTime = System.currentTimeMillis();
		log.info("==========================================================================");
		log.info("在" + serverIp + "上恢复完成，用时:" + (this.endTime - this.startTime) / 1000 + " 秒");
		log.info("恢复文件：" + this.recoverCount + " 个");
		log.info("删除文件：" + this.deleteCount + " 个");
		log.info("==========================================================================");
	}


}
